const Base = require("./base.js");
const moment = require("moment");

module.exports = class extends Base {
  /**
   * 定制参数
   * @returns {Promise<*>}
   */
  async paramsAction() {
    let goods_id = this.post("goods_id");
    let class_id = this.post("class_id");
    const custom = await this.model("procustom")
      .alias("a")
      .field("b.*")
      .join({
        table: "custom_type",
        join: "left",
        as: "b",
        on: ["customid", "id"],
      })
      .where({ proid: goods_id })
      .order("sort")
      .select();
    const style = await this.model("prostyle")
      .alias("a")
      .field("b.*")
      .join({
        table: "custom_params",
        join: "left",
        as: "b",
        on: ["styleid", "id"],
      })
      .where({ proid: goods_id })
      .order("sort")
      .select();
    const mater = await this.model("promater")
      .alias("a")
      .field("a.promaterid,a.customid,a.ismain,b.*,d.grade,e.*")
      .join({
        table: "material",
        join: "left",
        as: "b",
        on: ["materialid", "materialid"],
      })
      .join([
        `(select * from ef_margrade where classid=${class_id}) c on a.materialid=c.materailid`,
      ])
      .join({
        table: "grade",
        join: "left",
        as: "d",
        on: ["c.gradeid", "d.gradeid"],
      })
      .join(["ef_proprice e on c.gradeid=e.gradeid and a.proid=e.proid"])
      .where({ "a.proid": goods_id, status: 1 })
      .order("porder")
      .select();

    //可选物料
    for (let i = 0; i < custom.length; i++) {
      let list = this.model("custom_params").getChildList(custom[i].id, style);
      custom[i].params_child = {};
      for (let j = 0; j < list.length; j++) {
        list[j].params_child_count =
          (await this.model("custom_paramchild")
            .where({ paramsid: list[j].id })
            .order("sort")
            .count()) || 0;
        if (list[j].checked == "T" && list[j].params_child_count > 0) {
          custom[i].params_child = await this.model("custom_paramchild")
            .where({ paramsid: list[j].id })
            .order("sort")
            .find();
        }
      }
      custom[i].custom_params = list;
      const materlist = this.model("custom_params").getList(
        custom[i].id,
        mater
      );
      custom[i].mater = materlist;
    }
    //版型
    let version = await this.model("version")
      .field('*,"F" checked')
      .where({ classid: class_id })
      .order("vorder")
      .select();
    //刺绣位置 typeid:0
    const wordsids = await this.model("prowords")
      .where({ proid: goods_id, typeid: 0 })
      .getField("words_id");
    let words =
      wordsids.length == 0
        ? []
        : await this.model("words")
            .field('*,"F" checked')
            .where({ id: ["IN", wordsids] })
            .order("words_sort")
            .select();
    // let words =await this.model('words').field('*,"F" checked').where({category_id: class_id}).order('words_sort').select();
    for (let i = 0; i < words.length; i++) {
      if (words[i].words_name == "无绣字" || words[i].words_name == "无") {
        words[i].checked = "T";
        break;
      }
    }
    //刺绣颜色 typeid:1
    const wordscolorids = await this.model("prowords")
      .where({ proid: goods_id, typeid: 1 })
      .getField("words_id");
    const wordscolor =
      wordscolorids.length == 0
        ? []
        : await this.model("words_color")
            .field('*,"F" checked')
            .where({ id: ["IN", wordscolorids] })
            .order("color_sort")
            .select();
    console.log(custom[0].mater);

    // 品类量身类型
    // const volumeId = await this.model("goods")
    //   .where({ id: goods_id })
    //   .getField("volumeId");
    // const volumeType = await this.model("volume_type")
    //   .where({ id: volumeId })
    //   .getField("volume_list_tailored");

    return this.success({
      custom: custom,
      version: version,
      words: words,
      wordscolor: wordscolor,
      // volumeType: volumeType,
    });
  }

  async style_selectAction() {
    const d = this.post();
    const params_child = await this.model("custom_paramchild")
      .where({ paramsid: d.paramsid })
      .order("sort")
      .select();
    return this.success(params_child);
  }

  async material_listAction() {
    const d = this.post();
    const n = await this.model("matertype")
      .where({ id: d.customid })
      .getField("matertype");
    const material_list = await this.model("material")
      .where({ class: n[0] })
      .select();
    return this.success(material_list);
  }

  /**
   * 定制参数
   * @returns {Promise<*>}
   */
  async params_sizeAction() {
    const ids = await this.model("custom_type")
      .where({ category_id: 0 })
      .getField("id");
    const custom_type = await this.model("custom_type")
      .where({ id: ["IN", ids] })
      .select();
    const custom_params = await this.model("custom_params")
      .where({ custom_type: ["IN", ids] })
      .select();
    for (let i = 0; i < custom_type.length; i++) {
      const list = this.model("custom_params").getLists(
        custom_type[i].id,
        custom_params
      );
      custom_type[i].custom_params = list;
    }
    return this.success(custom_type);
  }

  /**
   * 标准尺码
   * @returns {Promise<void>}
   */
  async sizeAction() {
    // const data = await this.model('size').select();
    const d = this.post();
    if (Number(d.versionid) !== 0) {
      const data = await this.model("sizecode")
        .where({
          versionid: d.versionid,
          visible: 1,
        })
        .order("sorder")
        .select();
      return this.success(data);
    } else {
      const data = await this.model("sizecode").select();
      return this.success(data);
    }
  }

  /**
   * 标准尺码
   * @returns {Promise<void>}
   */
  async size_detailsAction() {
    // const data = await this.model('size').select();
    const d = this.post();
    const size = await this.model("sizecode")
      .where({
        sizecodeid: d.sizecodeid,
      })
      .find();
    const user_size = await this.model("user_size")
      .where({
        phone: d.phone,
      })
      .find();

    const list = await this.model("sizecode")
      .alias("a")
      .field("a.sizecodeid,a.title,b.sizeid,b.size")
      .join(["ef_size b on a.sizeid=b.sizeid"])
      .where({
        versionid: size.versionid,
      })
      .setRelation(false)
      .select();
    return this.success({ size: size, user_size: user_size, list: list });
  }

  /**
   * 腰围参数
   * @returns {Promise<void>}
   */
  async waistAction() {
    const data = await this.model("waist_size")
      .where({ status: 0 })
      .order("sort")
      .select();
    return this.success(data);
  }

  /**
   * 查询用户尺寸
   * @returns {Promise<any | void>}
   */
  async userSizeAction() {
    const result = await this.model("user_size")
      .where({
        user_id: think.user.user_id,
      })
      .order("is_default DESC,update_time DESC")
      .select();
    return this.success(result);
  }

  /**
   * 用户信息添加
   * @returns {Promise<any | void>}
   */
  async usersizeaddAction() {
    const d = this.post();
    await this.model("user_size").thenUpdate(
      {
        phone: d.phone,
        username: d.username,
        height: d.height,
        weight: d.weight,
        parter_id: think.user.user_id,
      },
      { phone: d.phone }
    );
    return this.success(true);
  }

  /**
   * 查询用户尺寸
   * @returns {Promise<any | void>}
   */
  async userSizePhoneAction() {
    // const size = await this.model('sizecode').where({
    //     sizecodeid: d.sizecodeid
    // }).find();
    // const user_size = await this.model('user_size').where({
    //     phone: d.phone,
    // }).find();
    //
    // const list = await this.model('sizecode').alias('a').field('a.sizecodeid,a.title,b.sizeid,b.size').join([
    //     'ef_size b on a.sizeid=b.sizeid'
    // ]).where({
    //     versionid: size.versionid
    // }).setRelation(false).select();
    // return this.success({size: size, user_size: user_size, list: list});

    const d = this.post();
    const user_size = await this.model("user_size")
      .where({
        phone: d.user_phone,
        user_id: [">", 0],
      })
      .find();

    const custom_sizecode = await this.model("custom_sizecode")
      .where({
        memberid: user_size.user_id || 0,
        versionid: d.versionid,
      })
      .order("updatetime desc")
      .find();

    if (think.isEmpty(custom_sizecode)) {
      const sizecode = await this.model("sizecode")
        .where({
          versionid: d.versionid,
          visible: 1,
        })
        .order("sorder")
        .select();
      let index = 0;
      if (sizecode.length > 1) {
        let next_curr = 99999;
        for (let i = 0; i < sizecode.length; i++) {
          let height = 0;
          for (let j = 0; j < sizecode[i].sizepro.length; j++) {
            if (sizecode[i].sizepro[j].tailored.tailored == "身高") {
              height = sizecode[i].sizepro[j].size;
              break;
            }
          }
          let curr = height - user_size.height;
          if (curr < next_curr) {
            index = i;
            next_curr = curr;
          }
        }
      }
      return this.success({ user_size: user_size, sizecode: sizecode });
    } else {
      return this.success({
        user_size: user_size,
        custom_sizecode: custom_sizecode,
      });
    }
  }

  /**
   * 删除尺寸
   * @returns {Promise<void>}
   */
  async userSizeDelAction() {
    const result = await this.model("user_size")
      .where({
        user_id: think.user.user_id,
        id: this.post("size_id"),
      })
      .update({ status: -1 });
    return this.success("删除成功");
  }

  /**
   * 添加修改尺寸
   * @returns {Promise<void>}
   */
  async addSizeAction() {
    const d = this.post();
    const result = await this.model("user_size").thenUpdate(
      {
        user_id: think.user.user_id,
        username: d.name,
        age: d.age,
        height: d.height,
        weight: d.weight,
        waist_size: d.waist_size,
        chest: d.chest,
        shoulder: d.shoulder,
        abdomen: d.abdomen,
        back: d.back,
        thingh: d.thingh,
        other: d.other,
        img: d.img,
        is_default: d.is_default,
        update_time: moment().format("YYYY-MM-DD HH:mm:ss"),
      },
      { id: d.size_id }
    );
    if (d.is_default === 1) {
      const update_default = await this.model("user_size")
        .where({
          user_id: think.user.user_id,
          id: ["!=", result],
          is_default: 1,
        })
        .update({ is_default: 0 });
    }
    return this.success("添加成功");
  }

  /**
   * 失败尺寸是否存在
   * @returns {Promise<void>}
   */
  async sizeExistAction() {
    const result = await this.model("user_size")
      .where({
        user_id: think.user.user_id,
        id: this.post("size_id"),
        status: 0,
      })
      .find();
    if (think.isEmpty(result)) {
      return this.success("F");
    }
    return this.success("T");
  }

  /**
   * 默认设置
   * @returns {Promise<void>}
   */
  async checkDefaultAction() {
    const size_id = this.post("size_id");
    const update_default = await this.model("user_size")
      .where({
        user_id: think.user.user_id,
        id: size_id,
      })
      .update({ is_default: 1 });
    const update_default_other = await this.model("user_size")
      .where({
        user_id: think.user.user_id,
        id: ["!=", size_id],
        is_default: 1,
      })
      .update({ is_default: 0 });

    const result = await this.model("user_size")
      .where({
        user_id: think.user.user_id,
        status: 0,
      })
      .order("is_default DESC,update_time DESC")
      .select();
    return this.success(result);
  }
};
